import { defineStore } from 'pinia'
import Web3 from 'web3'

export const useAuthStore = defineStore('auth', {
  state: () => ({
    isAuthenticated: localStorage.getItem('isAuthenticated') === 'true' || false,
    userRole: localStorage.getItem('userRole') || '',
    userInfo: JSON.parse(localStorage.getItem('currentUser')) || null,
    blockchainAccount: localStorage.getItem('blockchainAccount') || null,
    registeredUsers: JSON.parse(localStorage.getItem('registeredUsers')) || [],
    web3: null,
    walletConnected: false
  }),
  
  actions: {
    // 初始化Web3和钱包连接
    async initWeb3() {
      if (this.web3 && this.walletConnected) {
        return true // 已经连接则直接返回
      }

      if (typeof window.ethereum === 'undefined') {
        throw new Error('请安装MetaMask钱包扩展')
      }
      
      try {
        // 请求账户访问权限
        const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' })
        
        if (!accounts || accounts.length === 0) {
          throw new Error('未获取到钱包账户')
        }

        // 创建Web3实例
        this.web3 = new Web3(window.ethereum)
        this.walletConnected = true
        this.blockchainAccount = accounts[0]
        localStorage.setItem('blockchainAccount', this.blockchainAccount)
        
        // 监听账户变化
        window.ethereum.on('accountsChanged', this.handleAccountsChanged)
        
        return true
      } catch (error) {
        this.walletConnected = false
        this.blockchainAccount = null
        throw error
      }
    },
    
    // 处理账户变化
    handleAccountsChanged(accounts) {
      if (accounts.length === 0) {
        this.disconnectWallet()
      } else {
        this.blockchainAccount = accounts[0]
        localStorage.setItem('blockchainAccount', this.blockchainAccount)
        if (this.isAuthenticated) {
          // 如果已登录，更新用户信息中的钱包地址
          this.setUserInfo({ blockchainAccount: this.blockchainAccount })
        }
      }
    },
    
    // 断开钱包连接
    disconnectWallet() {
      this.walletConnected = false
      this.web3 = null
      
      if (!this.isAuthenticated) {
        this.blockchainAccount = null
        localStorage.removeItem('blockchainAccount')
      }
      
      if (window.ethereum) {
        window.ethereum.removeListener('accountsChanged', this.handleAccountsChanged)
      }
    },
    
    // 钱包登录方法
    async walletLogin(role = 'patient') {
      if (!this.walletConnected || !this.blockchainAccount) {
        throw new Error('请先连接钱包')
      }
      
      // 检查钱包地址是否已注册
      const existingUser = this.registeredUsers.find(
        user => user.blockchainAccount?.toLowerCase() === this.blockchainAccount.toLowerCase()
      )
      
      if (existingUser) {
        // 如果已注册，直接登录
        return this.login({
          username: existingUser.username,
          password: existingUser.password,
          role: existingUser.role
        })
      }
      
      // 自动创建账户
      const username = `user_${this.blockchainAccount.substring(2, 8)}`
      const password = Math.random().toString(36).slice(-8)
      
      const newUser = {
        username,
        password,
        role,
        blockchainAccount: this.blockchainAccount,
        timestamp: new Date().toISOString(),
        phone: '',
        realName: '',
        age: '',
        idCard: '',
        medicalHistory: '',
        bloodType: '',
        allergies: '',
        chronicDiseases: '',
        primaryDoctor: ''
      }
      
      this.registeredUsers.push(newUser)
      localStorage.setItem('registeredUsers', JSON.stringify(this.registeredUsers))
      
      // 自动登录
      return this.login({
        username,
        password,
        role
      })
    },
    
    // 设置用户信息
    setUserInfo(updatedInfo) {
      if (!this.userInfo) return
      
      // 更新当前用户信息
      this.userInfo = { 
        ...this.userInfo, 
        ...updatedInfo 
      }
      
      // 更新注册用户列表
      const userIndex = this.registeredUsers.findIndex(
        u => u.username === this.userInfo.username
      )
      
      if (userIndex !== -1) {
        const updatedUsers = [...this.registeredUsers]
        updatedUsers[userIndex] = { 
          ...updatedUsers[userIndex], 
          ...updatedInfo,
          // 保留原始密码和角色信息
          password: updatedUsers[userIndex].password,
          role: updatedUsers[userIndex].role,
          blockchainAccount: updatedUsers[userIndex].blockchainAccount
        }
        
        this.registeredUsers = updatedUsers
        localStorage.setItem('registeredUsers', JSON.stringify(updatedUsers))
      }
      
      // 更新当前用户存储
      localStorage.setItem('currentUser', JSON.stringify(this.userInfo))
      
      return this.userInfo
    },
    
    // 登录方法
    login(credentials) {
      const { username, password, role } = credentials;
      
      // 1. 验证用户存在性
      const userExists = this.registeredUsers.some(
        user => user.username === username
      );
      if (!userExists) {
        throw new Error('用户不存在，请先注册');
      }

      // 2. 验证用户凭证
      const validUser = this.registeredUsers.find(
        user => user.username === username && user.password === password
      );
      
      if (!validUser) {
        throw new Error('用户名或密码错误');
      }
      
      // 3. 验证用户角色
      if (validUser.role !== role) {
        throw new Error(`角色不匹配，该用户为${validUser.role}身份`);
      }

      // 所有验证通过后登录
      this.isAuthenticated = true;
      this.userRole = role;
      this.userInfo = validUser;
      this.blockchainAccount = validUser.blockchainAccount || null;

      // 更新本地存储
      localStorage.setItem('isAuthenticated', 'true');
      localStorage.setItem('userRole', role);
      localStorage.setItem('currentUser', JSON.stringify(validUser));
      localStorage.setItem('blockchainAccount', this.blockchainAccount);
      
      return true;
    },
    
    // 登出方法
    logout() {
      this.isAuthenticated = false;
      this.userRole = '';
      this.userInfo = null;
      this.blockchainAccount = null;
      this.walletConnected = false;
      this.web3 = null;

      localStorage.removeItem('isAuthenticated');
      localStorage.removeItem('userRole');
      localStorage.removeItem('currentUser');
      localStorage.removeItem('blockchainAccount');
      
      // 移除事件监听
      if (window.ethereum) {
        window.ethereum.removeListener('accountsChanged', this.handleAccountsChanged);
      }
    },
    
    // 注册方法
    register(userData) {
      const { username, password, role, blockchainAccount } = userData;
      
      // 检查用户是否已存在
      if (this.registeredUsers.some(user => user.username === username)) {
        throw new Error('该用户名已被注册');
      }

      // 创建完整用户对象
      const newUser = {
        username,
        password,
        role,
        blockchainAccount,
        timestamp: new Date().toISOString(),
        // 初始化用户信息字段
        phone: '',
        realName: '',
        age: '',
        idCard: '',
        medicalHistory: '',
        bloodType: '',
        allergies: '',
        chronicDiseases: '',
        primaryDoctor: ''
      };

      this.registeredUsers.push(newUser);
      localStorage.setItem('registeredUsers', JSON.stringify(this.registeredUsers));
      
      // 自动登录新注册用户
      this.login({ username, password, role });
      
      return newUser;
    },
    
    // 检查用户是否已注册
    isUserRegistered(username) {
      return this.registeredUsers.some(user => user.username === username);
    },
    
    // 获取用户角色
    getUserRole(username) {
      const user = this.registeredUsers.find(u => u.username === username);
      return user ? user.role : null;
    }
  }
})